# coding=utf8
from models.search import model_aliexpress_order, model_search


def statics_1():
    statics_map = {}
    for item in model_aliexpress_order.find():
        if item['CountryCode'] not in statics_map:
            statics_map[item['CountryCode']] = {}
        if item['ProductId'] not in statics_map[item['CountryCode']]:
            statics_map[item['CountryCode']][item['ProductId']] = int(item['Quantity'])
        else:
            statics_map[item['CountryCode']][item['ProductId']] += int(item['Quantity'])

    for country_code, map in statics_map.items():
        statics_list = ['商品名,交易记录,销量']
        for product_id, quantity in map.items():
            product = model_search.find_one({'ProductId': product_id})
            order_num = model_aliexpress_order.find({'ProductId': product_id, 'CountryCode': country_code}).count()
            statics_list.append(','.join([
                product['ItemName'].replace(",", "，"), str(order_num), str(quantity)
            ]))
        with open("data/sexual_{code}.csv".format(code=country_code), 'w', encoding='utf-8-sig') as f:
            f.write("\n".join(statics_list))


def statics_2():
    country_set = model_aliexpress_order.distinct('CountryCode')
    statics_map = {}
    for item in model_aliexpress_order.find():
        if item['ProductId'] not in statics_map:
            statics_map[item['ProductId']] = {}
        if item['CountryCode'] not in statics_map[item['ProductId']]:
            statics_map[item['ProductId']][item['CountryCode']] = int(item['Quantity'])
        else:
            statics_map[item['ProductId']][item['CountryCode']] += int(item['Quantity'])

    statics_list = []
    statics_list_title = ['商品名称,单价,单位']
    for code in country_set:
        statics_list_title.append(code + '_订单')
        statics_list_title.append(code + '_销量')
    statics_list.append(','.join(statics_list_title))

    for product_id, pmap in statics_map.items():
        product = model_search.find_one({'ProductId': product_id})
        order = model_aliexpress_order.find_one({'ProductId': product_id})
        item_list = [product['ItemName'].replace(",", "，"), str(product['Price']), order['Unit']]
        print(item_list)
        for country_code in country_set:
            order_num = model_aliexpress_order.find({'ProductId': product_id, 'CountryCode': country_code}).count()
            item_list.append(str(order_num))
            if country_code in pmap:
                item_list.append(str(pmap[country_code]))
            else:
                item_list.append('0')
        statics_list.append(','.join(item_list))

    with open("data/sexual_statics.csv".format(), 'w', encoding='utf-8-sig') as f:
        f.write("\n".join(statics_list))


statics_1()
statics_2()